<?php

namespace app\admin\controller\depot;

use app\common\controller\Backend;
use app\common\model\Business\Business;
use app\common\model\Depot\Back\Back;
use app\common\model\Depot\Storage\Product as StorageProduct;
use app\common\model\Depot\Storage\Storage as StorageStorage;
use app\common\model\Depot\Supplier;
use app\common\model\Order\Product as OrderProduct;
use app\common\model\Product\Product;
use Exception;
use fast\Random;
use think\Db;
use think\exception\ValidateException;
use think\exception\PDOException;
/**
 * 入库管理
 *
 * @icon fa fa-circle-o
 */
class Storage extends Backend
{

    /**
     * Storage模型对象
     * @var \app\admin\model\depot\Storage
     */
    protected $model = null;
    protected $supplierModel = null;
    protected $productModel = null;
    protected $storageProductModel = null;
    protected $backModel = null;
    protected $orderProductModel = null;
    protected $businessModel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new StorageStorage();
        $this->supplierModel = new Supplier();
        $this->productModel = new Product();
        $this->storageProductModel = new StorageProduct();
        $this->orderProductModel = new OrderProduct();
        $this->backModel = new Back();
        $this->businessModel = new Business();
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->assignconfig("supplierList", $this->supplierModel->getSupplierList());
        $this->relationSearch = true;
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

     public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        $filter = json_decode($this->request->get('filter'),true);
         $op = json_decode($this->request->get('op'),true);
         if (isset($filter['supplier.name'])){
             $filter['supplier.id'] = $filter['supplier.name'];
             $op['supplier.id'] = $op['supplier.name'];
             unset($filter['supplier.name']);
             unset($op['supplier.name']);
         }
         $this->request->get(['filter'=>json_encode($filter)]);
         $this->request->get(['op'=>json_encode($op)]);

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['supplier'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
            foreach ($list as $key => $item) {
                if($item['type']=='2'){
                    $back = $this->backModel->where('storageid',$item['id'])->find();
                    if($back&&$back['expresscode']){
                        $item['isback'] = true;
                    }else{
                        $item['isback'] = false;
                    }
                    $list->offsetSet($key, $item);
                }
            }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    public function add()
    {
        if (false === $this->request->isPost()) {
            $supplierList = build_select('row[supplierid]',$this->supplierModel->getSupplierList(),[],['class'=>'selectpicker', 'required'=>'']);
            $this->assign('supplierList',$supplierList);
            $productList = build_select('row[proid][]',$this->productModel->column('id,name'),[],['class'=>'selectpicker', 'required'=>'']);
            $this->assign('productList',$productList);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['type'] = '1';
            $params['code'] = 'ST'.date('YmdHis',time()).Random::numeric(7);
            $params['status'] = '0';
            $result = $this->model->allowField(true)->create($params);
            $paramsList = [];
            $amount	= 0;
            if(!isset($params['proid'])||count($params['proid']))throw new Exception(__('Parameter %s can not be empty',''));
            foreach($params['proid'] as $key=>$propid)
            {
                $total = $params['nums'][$key]*$params['price'][$key];
                $amount += $total;
                $paramsList[] = [
                    'storageid'=>$result['id'],
                    'proid'=>$propid,
                    'nums'=>$params['nums'][$key],
                    'price'=>$params['price'][$key],
                    'total'=>$total,
                ];
            }
            if($amount!=floatval($params['amount']))throw new Exception(__('Amount discrepancy'));
            $this->storageProductModel->allowField(true)->saveAll($paramsList);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    public function review($ids)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        $status = $this->request->get("status",'0','trim');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                if($item['type']==2){
                    $back = $this->backModel->where('storageid',$item['id'])->find();
                    ($status==2)?($back['status'] = '1'):($back['status'] = '-1');
                    $back['reviewerid'] = $this->auth->id;
                    $back->isUpdate()->save();
                }
                if($item['status']!='0')throw new Exception(__('Reviewed'));
                $item['status'] = $status;
                $item['reviewerid'] = $this->auth->id;
                $count += ($item->isUpdate()->save())?1:0;
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were review'));
    }
    public function warehouse($ids)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        $status = $this->request->get("status",'0','trim');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();
        $count = 0;
        Db::startTrans();
        try {
            $storageProductList = $this->storageProductModel->where('storageid', 'in', $ids)->select();
            foreach ($storageProductList as $storageProduct) {
                //product
                $product = $this->productModel->get($storageProduct['proid']);
                $product['stock'] += $storageProduct['nums'];
                $product->isUpdate()->save();
            }
            foreach ($list as $item) {
                if($item['status']!='2')throw new Exception(__('Warehoused'));
                $item['status'] = $status;
                $item['adminid'] = $this->auth->id;
                $count += ($item->isUpdate()->save())?1:0;
                if($item['type']=='2'){
                    //back
                    $back = $this->backModel->where('storageid',$item['id'])->find();
                    $back['status'] = '2';
                    $back->isUpdate()->save();
                    //orderProduct
                    $orderProduct = $this->orderProductModel->where('code',$back['ordercode'])->find();
                    $orderProduct['status'] = '-4';
                    $orderProduct->isUpdate()->save();
                    //business
                    $business = $this->businessModel->get($orderProduct['busid']);
                    $business['money'] += $orderProduct['total'];
                    $business->isUpdate()->save();
                }
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were warehouse'));
    }
}
